/*
 * @lc app=leetcode.cn id=8 lang=java
 *
 * [8] 字符串转换整数 (atoi)
 */

// @lc code=start
class Solution {

    /**
     * 1088/1088 cases passed (1 ms)
    Your runtime beats 100 % of java submissions
    Your memory usage beats 90.97 % of java submissions (40.1 MB)
     */
    public int myAtoi(String s) {
        int result = 0;
        int index = 0;
        char pre = '+';
        boolean b = true;

        String r = s.trim();
        int len = r.length();

        if (len < 1)
            return 0;

        char c0 = r.charAt(0);

        if (c0 == '+' || c0 == '-') {
            index = 1;
            pre = c0;
        }

        while (b && index < len) {
            char c = r.charAt(index);
            if (c >= '0' && c <= '9') {
                int t = c - '0';
                if (pre == '-') {
                    if (result < Integer.MIN_VALUE / 10 || Integer.MIN_VALUE + t > result * 10) {
                        return Integer.MIN_VALUE;
                    } else {
                        result = result * 10 - t;
                        index++;
                    }
                } else {
                    if (result > Integer.MAX_VALUE / 10 || Integer.MAX_VALUE - t < result * 10) {
                        return Integer.MAX_VALUE;
                    } else {
                        result = result * 10 + t;
                        index++;
                    }
                }
            } else {
                b = false;
            }
        }
        return result;
    }
}
// @lc code=end
